package interrupt;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author fei
 * @date 2023/1/9 16:48
 * @description 中断运行中的线程
 */
public class InterruptDemo {

    static volatile boolean isStop = false;
    static AtomicBoolean atomicBoolean = new AtomicBoolean();

    public static void main(String[] args) {
        // m1_volatile();
        // m2_atomicBoolean();
        Thread t1 = new Thread(() -> {
            while (true){
                // Thread.currentThread(): 获取当前线程
                // isInterrupted()：判断当前线程是否被中断（通过检查中断标志位）
                if (Thread.currentThread().isInterrupted()){
                    System.out.println(Thread.currentThread().getName() + "\t isInterrupted() 被修改为 true, 程序停止");
                    break;
                }
                System.out.println("t1 -------hello interrupt api");
            }
        }, "t1");
        t1.start();

        System.out.println("t1 ------默认 isInterrupted：" + t1.isInterrupted());

        // 暂停毫秒
        try{ TimeUnit.MILLISECONDS.sleep(20);} catch (InterruptedException e) { e.printStackTrace(); }

        new Thread(() -> {
            // 仅仅是是设置线程的中断状态为 true，发起一个协商而不会立刻停止线程
            t1.interrupt();
        }, "t2").start();
    }

    private static void m2_atomicBoolean() {
        new Thread(() -> {
            while (true){
                if (atomicBoolean.get()){
                    System.out.println(Thread.currentThread().getName() + "\t atomicBoolean 被修改为 true, 程序停止");
                    break;
                }
                System.out.println("t1 -------- hello atomicBoolean");
            }
        }, "t1").start();

        // 暂停毫秒
        try{ TimeUnit.MILLISECONDS.sleep(20);} catch (InterruptedException e) { e.printStackTrace(); }

        new Thread(() -> {
            atomicBoolean.set(true);
        }, "t2").start();
    }

    private static void m1_volatile() {
        new Thread(() -> {
            while (true){
                if (isStop){
                    System.out.println(Thread.currentThread().getName() + "\t isStop 被修改为 true, 程序停止");
                    break;
                }
                System.out.println("t1 -------- hello volatile");
            }
        }, "t1").start();

        // 暂停毫秒
        try{ TimeUnit.MILLISECONDS.sleep(20);} catch (InterruptedException e) { e.printStackTrace(); }

        new Thread(() -> {
            isStop = true;
        }, "t2").start();
    }

}
